<template>
  <div id="app">
    <!-- 顶部导航栏 -->
    <nav class="navbar">
      <img src="/logo.png" alt="图表信息" class="icon" />
      <ul>
        <li><router-link to="/main">首页</router-link></li>
        <li><router-link to="/compare">商品比价</router-link></li>
        <li><router-link to="/webdate">销售统计</router-link></li>
        <!-- 添加更多导航链接 -->
      </ul>
    </nav>
    <!-- 查询 -->
    <div class="card-container">
      <div class="card">
        <el-form :inline="true" :model="frmQuery" class="demo-form-inline">
          <el-form-item label="商品名称">
            <el-input
              v-model="frmQuery.product_name"
              placeholder="请输入商品名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="品牌名称">
            <el-input
              v-model="frmQuery.brand_name"
              placeholder="请输入品牌名称"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="btnQuery">查询</el-button>
          </el-form-item>

          <div v-if="errorMessage" class="error-message">
            {{ errorMessage }}
          </div>
        </el-form>
        <div class="product-container">
          <div
            class="product-card"
            v-for="(product, index) in tableData"
            :key="index"
            :style="{
              'margin-right': index % 5 !== 4 ? '10px' : '0', // 添加右边距，但每行的最后一个产品不需要
              marginBottom: '10px', // 你可以根据需要添加底部边距
            }"
          >
            <a :href="product.product_link" target="_blank">
              <!-- target="_blank" 可选，表示在新标签页打开 -->
              <img
                :src="product.image_url"
                alt="产品图片"
                style="width: 100%; height: auto"
              />
            </a>
            <p class="product-name">{{ product.product_name }}</p>
            <p class="product-price">￥{{ product.price }}</p>
          </div>
        </div>
        <!-- 表格列内容 -->

        <br />
        <!-- 分页 -->

        <div>
          <!-- 列表数据渲染区域 -->
          <div v-for="item in paginatedData" :key="item.id">
            <!-- 渲染列表项 -->
            {{ item.name }}
          </div>

          <!-- 分页控件 -->
          <div class="pagination">
            <button @click="prevPage" :disabled="currentPage === 1">
              上一页
            </button>
            <span>第 {{ currentPage }} 页 / 总共 {{ totalPages }} 页</span>
            <button @click="nextPage" :disabled="currentPage === totalPages">
              下一页
            </button>
            <div v-if="errorMessage" class="error-message">
              {{ errorMessage }}
            </div>
            <select v-model="pageSize" @change="handleSizeChange(pageSize)">
              <option value="10">10个/页</option>
              <option value="25">25个/页</option>
              <option value="50">50个/页</option>
              <!-- 其他选项... -->
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
export default {
  data() {
    return {
      classificationList: [], // 存放分类数据的数组
      currentPage: 1, // 当前页码
      pageSize: 50,
      totalItems: 0,
      paginatedData: [], // 当前页的数据
      rawData: [], // 原始数据数组
      pageInfo: {},
      errorMessage: "", // 用于存储错误信息的属性
      options: [
        {
          value: "zhinan",
          label: "淘宝",
          children: [
            {
              value: "shejiyuanze",
              label: "衣服",
            },
            {
              value: "shejiyuanze",
              label: "手机",
            },
            {
              value: "shejiyuanze",
              label: "平板",
            },
            {
              value: "shejiyuanze",
              label: "鞋子",
            },
          ],
        },
        {
          value: "ziyuan",
          label: "京东",
          children: [
            {
              value: "axure",
              label: "衣服",
            },
            {
              value: "sketch",
              label: "手机",
            },
            {
              value: "jiaohu",
              label: "平板",
            },
            {
              value: "jiaohu",
              label: "鞋子",
            },
          ],
        },
      ],
      value1: [],
      value2: [],
      currentPage: 1,
      pageSize: 10,
      pageInfo: {},
      frmQuery: {
        product_name: "", // 商品名称的输入值
        brand_name: "", // 品牌名称的输入值
        searchResults: [], // 用于存储搜索结果的属性
      },
      randomProducts: [],
      formLabelWidth: "140px",
      tableData: [],
      errorMessage: "", // 用于显示错误的变量
      total: 0, // 数据总数，用于分页
      classData: [],
      pageInfo1: {},
    };
  },
  mounted() {
    this.fetchClassifications();
    this.getTestData();
  },
  computed: {
    totalPages() {
      return Math.ceil(this.totalItems / this.pageSize);
    },
  },
  methods: {
    getTestData() {
      // 发送 GET 请求到指定接口
      axios
        .get("http://localhost:8080/classification/alldata", {
          params: {
            pageNum: 1,
            pageSize: 10,
          },
        })
        .then((response) => {
          console.log(response.data);
          this.tableData = response.data;
        })
        .catch((error) => {
          // 处理错误
          console.error("Error fetching data:", error);
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchClassifications(); // 更新数据
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchClassifications(); // 更新数据
    },
    async fetchClassifications() {
      try {
        // 注意这里的URL和参数应该与您的后端API匹配
        const response = await axios.get(
          `http://localhost:8080/classification/by-conditions?platformName=&categoryName=&pageNum=${this.currentPage}&pageSize=${this.pageSize}`
        );
        // 根据当前页码和每页大小计算起始索引
        this.paginatedData = response.data.list; // 使用后端返回的数据作为当前页数据
        this.totalItems = response.data.total; // 更新总数  // 假设后端还返回了总记录数
        this.errorMessage = "";
      } catch (error) {
        console.error("Error fetching classifications:", error);
        this.errorMessage = "当前没有数据，请您尝试搜索"; // 更新错误信息
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
        this.fetchClassifications();
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        this.fetchClassifications();
      }
    },

    btnQuery() {
      // 获取输入值
      const product_name = this.frmQuery.product_name;
      const brand_name = this.frmQuery.brand_name;

      // 构造完整的URL，并将查询参数附加到URL上
      const url = `http://localhost:8080/search/search?product_name=${product_name}&brand_name=${brand_name}`;

      // 发送GET请求到后端
      axios
        .get(url)
        .then((response) => {
          // 处理成功的响应
          this.tableData = response.data; // 假设后端返回的是搜索结果数组
          this.errorMessage = ""; // 清空错误信息
          console.log(response.data);
        })
        .catch((error) => {
          // 处理错误
          console.error(error);
          this.errorMessage = "查询失败，请稍后重试。"; // 设置错误信息
        });
    },
    LoadData() {
      // Your existing method implementation...
    },

    deleteClick(t_uid) {
      // Your existing method implementation...
    },
    btnAddDialog() {
      this.form = {}; // 清空表单
      this.dialogTitle = "添加问卷信息";
      this.dialogFormVisible = true;
    },
    addUser() {
      // Your existing method implementation...
    },
    updateUser() {
      // Your existing method implementation...
    },
    updateDialog(t_uid) {
      // Your existing method implementation...
    },
    getContext() {
      // Your existing method implementation...
    },
    LoadClassData() {
      // Your existing method implementation...
    },
  },
  created() {
    this.fetchClassifications();
  },
};
</script>

<style scoped>
#app {
  display: flex;
  flex-direction: column;
  height: 100vh; /* 使应用占据整个视口高度 */
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.navbar {
  /* 固定在顶部 */
  top: 0;
  left: 0;
  right: 0;
  height: 100px; /* 设置导航栏高度 */
  background-color: #333; /* 设置背景颜色 */
  display: flex;
  align-items: center; /* 垂直居中 */
}
.navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  padding-left: 50px; /* 设置内边距，让文字离左边有一定的距离 */
}
.navbar li {
  margin: 0 10px;
}
.navbar li a {
  color: white;
  text-decoration: none;
}

.product-price {
  color: red; /* 将价格颜色设置为红色 */
}
.product-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.product-card {
  flex: 0 0 18%; /* 假设每个卡片占 18% 的宽度，加上 10px 的右边距，大约是 20% */
  margin-bottom: 20px; /* 垂直间距 */
  box-sizing: border-box; /* 确保边距和边框包含在元素的总宽度和总高度内 */
  border: 1px solid #ddd; /* 可选：添加边框 */
  padding: 0; /* 可选：添加内边距 */
}
.product-name {
  margin-top: 10px; /* 在图片下方添加一些间距 */
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.box-card {
  width: 100%;
}
.center-content {
  text-align: center; /* 文本居中 */
  display: flex; /* 使用 Flexbox */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中（对于单行flex容器）*/
}
</style>
